package com._520it.crm.web.controller;

import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by seemygo on 2017/9/28.
 */
@ControllerAdvice
public class ExceptionHanlder {
    @ExceptionHandler(UnauthorizedException.class)
    public void handlerException(HandlerMethod handlerMethod, HttpServletResponse response) {
        try{
            //根据请求方法判断是否有@ResponseBody标签,如果有说明是ajax,如果没有是页面请求
            if(handlerMethod.getMethodAnnotation(ResponseBody.class)!=null){
                //Ajax请求,返回JSON格式数据 {"success":false,"msg":"您没有权限!",total:0,rows:[]}
                //  保存,更新,删除  {"success":false,"msg":"您没有权限!"}
                //  列表           {total:0,rows:[]}
                response.setCharacterEncoding("utf-8");
                response.getWriter().write("{\"success\":false,\"msg\":\"您没有权限!\",\"total\":0,\"rows\":[]}");
            }else{
                //页面请求,如果没有权限,重定向到/nopermission.jsp
                response.sendRedirect("/nopermission.jsp");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
